#include "MavenSearch.h"
#include "MavenResult.h"
#include "NetworkRequest.h"

#include <QTextStream>
#include <QJsonDocument>
#include <QJsonValue>
#include <QJsonObject>
#include <QJsonArray>


MavenSearch::MavenSearch(QObject *parent) : QObject(parent)
,request(new NetworkRequest)
,URL("https://search.maven.org/solrsearch/select?")
,keyword("")
{
    connect(request, &NetworkRequest::replyRequest, [=](const QString &content){
        QJsonObject object = QJsonDocument::fromJson(content.toLocal8Bit()).object();
        QJsonArray docs = object.value("response").toObject().value("docs").toArray();
        
        m_results.clear();
        for (int i = 0; i < docs.size(); i++) {
            MavenResult *result = new MavenResult;
            result->setValue(docs.at(i).toObject());
            m_results.append(result);
        }

        
        if (docs.size() > 0) {
            m_oldresults.clear();
            m_oldresults.append(m_results);
            emit this->docs(m_oldresults);
        }
    });

}

MavenResult* MavenSearch::getResult(QString id) {
    QTextStream stream(stdout);
    // stream << QString("(result) ==> (%1)\n").arg(m_oldresults.size());

    for (auto *result : m_oldresults)
    {  
        // stream << QString("(%1)startsWith (%2): %3\n").arg(id).arg(result->id).arg(id.startsWith(result->id));
        if (result->id.split(":").count() == 2) {
            if (id.startsWith(QString("%1:").arg(result->id))) {
                return result;
            }
        } else {
            if (id == result->id) {
                return result;
            }
        }
    }
    return nullptr;
}

void MavenSearch::search(QString search, int rows, QString wt) {
    QString url = QString("%1q=%2&rows=%3&wt=%4")
                    .arg(URL)
                    .arg(search)
                    .arg(rows)
                    .arg(wt);

    request->requestString(url);
}

void MavenSearch::searchAllVersion(QString search, int rows, QString wt) {
    QString url = QString("%1q=%2&rows=%3&wt=%4&core=gav")
                    .arg(URL)
                    .arg(search)
                    .arg(rows)
                    .arg(wt);

    request->requestString(url);
}

/*************************

https://search.maven.org/solrsearch/select?q=junit&rows=20&wt=json

url:
    https://search.maven.org/solrsearch/select?
params:
    q=junit &rows=20 &wt=json

URL = "https://search.maven.org/solrsearch/select?"
void search(QString search, int rows, QString wt);
QString("%1q=%2&rows=%3&wt=%4").arg(URL).arg(search).arg(rows).arg(wt)


*************************/